package com.zhida.jiyangcenter.account

import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.manager.app
import chooongg.base.utils.*
import chooongg.http.APIException
import chooongg.http.HttpCallback
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.WebNoTokenActivity
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.LoginEntity
import com.zhida.jiyangcenter.api.NetResponse
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.MainActivity
import com.zhida.jiyangcenter.utils.SP
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_login_code.*
import kotlinx.android.synthetic.main.activity_login_code.btn_wechat
import kotlinx.android.synthetic.main.activity_login_code.title_bar
import kotlinx.android.synthetic.main.activity_login_code.tv_login_other
import kotlinx.android.synthetic.main.activity_login_code.tv_login_xieyi
import kotlinx.android.synthetic.main.activity_login_code.tv_title
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@TitleBar(false)
@ContentLayout(R.layout.activity_login_code)
class LoginCodeActivity : BaseActivity() {
    override fun initConfig(savedInstanceState: Bundle?) {
        val window = activity.window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        val styles = SpannableStringBuilder() //设置文字
        val s = "登录注册即代表同意《用户使用协议》《隐私政策说明条款》"
        styles.append(s)
        val clickableSpans = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<WebNoTokenActivity> {
                    putExtra(WebNoTokenActivity.URL,"http://beauty.hebzd.com/static/xieyi/userAgreement.html")
                    putExtra(WebNoTokenActivity.TITLE,"用户使用协议")
                }
            }
        }
        styles.setSpan(clickableSpans, 9, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val foregroundColorSpans = ForegroundColorSpan(Color.parseColor("#1296DB"))
        styles.setSpan(foregroundColorSpans, 9, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) //配置给TextView
        val clickableSpan1 = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<WebNoTokenActivity> {
                    putExtra(WebNoTokenActivity.URL, "http://beauty.hebzd.com/static/xieyi/privacy.html")
                    putExtra(WebNoTokenActivity.TITLE, "隐私政策说明条款")
                }
            }
        }
        styles.setSpan(clickableSpan1, 18, styles.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val foregroundColorSpan1 = ForegroundColorSpan(Color.parseColor("#1296DB"))
        styles.setSpan(foregroundColorSpan1, 18, styles.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) //配置给TextView
        tv_login_xieyi.movementMethod = LinkMovementMethod.getInstance()
        tv_login_xieyi.text=styles
        tv_title.setText("登录后更精彩".style { } + "\n解锁更多功能  一站式管理你的健康".style {
            setTextSizeRelative(0.5f)
            setTextStyle(Typeface.NORMAL)
        })
        tv_code_phone.text = "已发送验证码至 +86 ${intent.getStringExtra("phone")}"
        tv_login_code_agent.setOnClickListener {
            lifecycleScope.launch {
                val s = APIAccount.service().sendCode(intent.getStringExtra("phone"))
                logE(s)
                authCodeCountDown()
            }
        }
        lifecycleScope.launch {
            authCodeCountDown()
        }
        ecv_code.setEditCodeListener {
            lifecycleScope.request({
                if (intent.getStringExtra("wechat_openid").isNullOrEmpty()) {
                    APIAccount.service().login(
                        intent.getStringExtra("phone") ?: "",
                        0,
                        referral_code = intent.getStringExtra("yaoqingma"),
                        code = it
                    )
                } else {
                    APIAccount.service().login(
                        intent.getStringExtra("phone") ?: "",
                        0,
                        code = it,
                        referral_code = intent.getStringExtra("yaoqingma"),
                        wechat_openid = intent.getStringExtra("wechat_openid")
                    )
                }
            }, object : BaseAPI<LoginEntity>() {

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

                override fun onSuccess(loginEntity: LoginEntity?, state: Int, msg: String) {
                    SP.isLogin.put(true)
                    SP.key_id.put(loginEntity?.key_id)
                    SP.account.put(loginEntity?.account)
                    SP.avatar.put(loginEntity?.avatar)
                    SP.EBusinessID.put(loginEntity?.business_id)
                    SP.AppKey.put(loginEntity?.app_key)
                    SP.ReqURL.put(loginEntity?.req_url)
                    if (loginEntity?.kind == 0 && intent.getStringExtra("wechat_openid")
                            .isNullOrEmpty()
                    ) {
                        startActivity<SetPassActivity> { }
                    } else {
//                        if (!SP.ISYinsi.get()) {
//                            startActivity<WebNoTokenActivity> {
//                                putExtra(
//                                    WebNoTokenActivity.URL,
//                                    "http://beauty.hebzd.com/static/xieyi/privacy.html"
//                                )
//                                putExtra(WebNoTokenActivity.TITLE, "隐私协议")
//                            }
//                        } else {
                            startActivity<MainActivity> { }
//                        }
                    }
                    for (i in app.activityStack.size - 1 downTo 0) {
                        if (app.activityStack[i] !is MainActivity) {
                            app.activityStack[i].finish()
                        }
                    }
                    finish()
                }
            })
        }
        if (intent.getStringExtra("wechat_openid").isNullOrEmpty()) {
            tv_login_other.visible()
            btn_wechat.visible()
            tv_login_xieyi.visible()
        } else {
            tv_login_other.gone()
            btn_wechat.gone()
            tv_login_xieyi.gone()
        }
        btn_wechat.setOnClickListener {
            val wechat = ShareSDK.getPlatform(Wechat.NAME)
            if (wechat.isAuthValid) wechat.removeAccount(true)// 解除本地授权信息
            //SSO授权，传false默认是客户端授权
            wechat.SSOSetting(false);
            wechat.platformActionListener = object : PlatformActionListener {
                override fun onComplete(
                    platform: Platform,
                    action: Int,
                    res: HashMap<String, Any>
                ) {
                    showTipLoading("登录中")
                    if (action == Platform.ACTION_USER_INFOR) {
                        wechatLogin(res["openid"].toString())
                    }
                }

                override fun onCancel(p0: Platform?, p1: Int) {
                    toast("取消授权")
                }

                override fun onError(p0: Platform?, errorCode: Int, e: Throwable?) {
                    toast("授权失败\n错误码：$errorCode")
                    Log.e("SDFSDFSDF", "dfwetwesfsdf", e)
                    e?.printStackTrace()
                }
            }
            wechat.showUser(null)
        }
    }

    private fun wechatLogin(toString: String) {
        lifecycleScope.request({ APIAccount.service().weCharLogin(toString) },
            object : BaseAPI<LoginEntity>() {
                override fun onSuccess(loginEntity: LoginEntity?, state: Int, msg: String) {
                    hideTipLoading()
                    if (loginEntity == null) {

                    } else {
                        tipSuccess(msg)
                        SP.isLogin.put(true)
                        SP.key_id.put(loginEntity.key_id)
                        SP.account.put(loginEntity.account)
                        SP.avatar.put(loginEntity.avatar)
                        SP.EBusinessID.put(loginEntity.business_id)
                        SP.AppKey.put(loginEntity.app_key)
                        SP.ReqURL.put(loginEntity.req_url)
//                        if (!SP.ISYinsi.get()){
//                            startActivity<WebNoTokenActivity> {
//                                putExtra(WebNoTokenActivity.URL, "http://beauty.hebzd.com/static/xieyi/privacy.html")
//                                putExtra(WebNoTokenActivity.TITLE, "隐私协议")
//                            }
//                        }else
                        startActivity<MainActivity> { }
                        for (i in app.activityStack.size - 1 downTo 0) {
                            if (app.activityStack[i] !is MainActivity) {
                                app.activityStack[i].finish()
                            }
                        }
                        finish()
                    }
                }

                override fun onError(e: APIException) {
                    hideTipLoading()
                    if (e.code == "-9") {
                        startActivity<LoginPhoneActivity> {
                            putExtra("wechat_openid", toString)
                        }
                    } else {
                        tipFail(e.eMessage)
                    }
                }

            })
    }

    /**
     * 发送验证码后的倒计时
     */
    private suspend fun authCodeCountDown() {
        var time = 61
        while (time > 0 && !isFinishing) {
            time--
            if (time > 0) {
                withContext(Dispatchers.Main) {
                    tv_login_code_agent.isClickable = false
                    tv_login_code_agent.text = resString(R.string.login_been_send_auth_code, time)
                }
            } else {
                withContext(Dispatchers.Main) {
                    tv_login_code_agent.setText(R.string.login_get_auth_code_retry)
                    tv_login_code_agent.isClickable = true
                }
            }
            delay(1000)
        }
    }
}